<template>
  <div class="container">
    <el-card>
      <header class="header-container">
        <span class="left-container">
          <el-button type="primary" icon="el-icon-back" @click="back" />
          <span style="font-weight: bold; margin-left: 12px;">{{ topData.companyNo }} {{ topData.companyName }}</span>
        </span>
      </header>
      <div style="margin-top: 16px;">
        <span>{{ topData.countryCode }}</span>
        <el-divider direction="vertical" />
        <span>{{ topData.sourceCode }}</span>
        <el-divider direction="vertical" />
        <span>{{ topData.marketLevelCode }}</span>
      </div>
    </el-card>
    <el-card style="margin-top: 12px; margin-bottom: 22px">
      <BankInfoCard title="银行卡信息" :list="bankCardInfo" description="暂无银行卡号信息" />
      <TableInfoCard
        title="流水核销信息"
        :table-data="writeOffInfo"
        :table-list="tableList"
        :total="writeTotal"
        :loading="writeOffInfoLoading"
        show-index
        show-pagination
        @pagination="handleWritePagination"
      >
        <el-table-column
          fixed="right"
          label="操作"
          width="86px"
        >
          <template v-slot="scope">
            <el-button type="text" @click="handleHistory(scope.row.id)">核销记录</el-button>
          </template>
        </el-table-column>
      </TableInfoCard>
      <InfoCard title="返点账户信息" :list="rebateAccountInfo" :style="style" />
      <InfoCard title="客户授信信息" :list="creditInfo" :style="style" />
      <el-tabs v-model="activeTab" :style="bottomStyle">
        <el-tab-pane label="返点明细" name="1">
          <Rebate v-if="activeTab==='1'" :name-list="flow_name_type" />
        </el-tab-pane>
        <el-tab-pane label="授信额度明细" name="2">
          <Credit v-if="activeTab==='2'" :name-list="flow_name_type" />
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      title="核销记录"
      :visible.sync="visible"
      :close-on-press-escape="false"
      width="60%"
      center
      @open="openWriteHistoryDialog"
    >
      <BaseTable
        :loading="historyListLoading"
        :table-data="historyList"
        :table-list="historyConfig"
        show-index
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">关闭</el-button>
      </span>
    </el-dialog>
    <BlockDialog v-if="curUrl" :url="curUrl" title="预览" :name="curName" @close="closeHandle" />
  </div>
</template>

<script>
import InfoCard from '@/views/applicationForm/components/InfoCard'
import BankInfoCard from './components/bankInfoCard'
import TableInfoCard from '@/views/applicationForm/components/TableInfoCard'
import BaseTable from '@/components/BaseTable'
import BlockDialog from '@/components/BlockDialog'
import Rebate from './components/Rebate'
import Credit from './components/Credit'
import { formatUserName, formatTime, isUndefined, getDictionaryLabel, isSfType, formatMoneyAmount } from '@/utils/tools'
import {
  accountDetail,
  bankList,
  rebateAccountData,
  getCreditInfo,
  writeOffRecordById
} from '@/service/accountManage'
import { cashBackPollList } from '@/service/cashBackPoll'
import { mapState, mapActions } from 'vuex'

// 需考虑接口没数据情形
const getEngross = (approveNumber, notApproveNumber) => {
  const sum = parseFloat(approveNumber) + parseFloat(notApproveNumber)
  const str = `${formatMoneyAmount(sum)} （其中发货申请已审批部分${approveNumber}，未审批部分${notApproveNumber}）`
  return str
}

export default {
  name: 'AccountDetail',
  components: {
    InfoCard,
    TableInfoCard,
    BaseTable,
    Rebate,
    Credit,
    BankInfoCard,
    BlockDialog
  },
  data() {
    return {
      id: '',
      writeOffInfoId: '', // 核销记录列表id
      curUrl: '',
      curName: '',
      writeOffInfoLoading: false,
      historyListLoading: false, // 核销记录历史列表loading
      allData: {},
      topData: {
        companyNo: '',
        companyName: '',
        countryCode: '',
        sourceCode: '',
        marketLevelCode: ''
      },
      bankCardInfo: [],
      writeOffInfo: [],
      writeTotal: 0,
      writePageIndex: 1,
      writePageSize: 10,
      tableList: [
        {
          label: '收款银行',
          prop: 'receivingBankName'
        },
        {
          label: '收款账号',
          prop: 'receivingBankAccount',
          width: '200px'
        },
        {
          label: '到账时间',
          prop: 'transactionDate',
          width: '134px',
          render: function(node, data) {
            const { row, column: { prop }} = data
            const text = formatTime(row[prop])
            return <span>{{ text }}</span>
          }
        },
        {
          label: '到账金额',
          prop: 'transactionAmount',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = formatMoneyAmount(row[prop])
            return <span>{text}</span>
          }
        },
        {
          label: '交易币种',
          prop: 'transactionCurrency',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = getDictionaryLabel(row[prop], this.currency)
            return <span>{text}</span>
          }
        },
        {
          label: '流水号',
          prop: 'transactionFlowNo'
        },
        {
          label: '摘要',
          prop: 'summary'
        },
        {
          label: '付款方名称',
          prop: 'payerName',
          width: '200px'
        },
        {
          label: '付款方账号',
          prop: 'payerAccount',
          width: '200px'
        },
        {
          label: '对应水单金额',
          prop: 'bankSlipAmount',
          width: '150px',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = formatMoneyAmount(row[prop])
            return <span>{text}</span>
          }
        },
        {
          label: '水单币种',
          prop: 'bankSlipCurrency',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = getDictionaryLabel(row[prop], this.currency)
            return <span>{text}</span>
          }
        },
        {
          label: '水单附件',
          prop: 'attachmentList',
          width: '300px',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const arr = row[prop]?.map(ele => {
              return <div style={{ color: 'blue' }}><a onClick={e => this.previewHandle(e, ele.attachmentUrl, ele.filename)}>{ele.filename}</a></div>
            })
            return <div>{arr}</div>
          }
        },
        {
          label: '是否财务变更',
          prop: 'financialModify',
          width: '120px',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = row[prop] ? '是' : '否'
            return <span>{text}</span>
          }
        },
        {
          label: '最终收款主体',
          prop: 'finalPayeeName',
          width: '200px'
        },
        {
          label: '最终收款账号',
          prop: 'finalReceivingBankAccount',
          width: '200px'
        },
        {
          label: '最终币种',
          prop: 'finalCurrency',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = getDictionaryLabel(row[prop], this.currency)
            return <span>{text}</span>
          }
        },
        {
          label: '最终金额',
          prop: 'finalAmount',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = formatMoneyAmount(row[prop])
            return <span>{text}</span>
          }
        },
        {
          label: '已核销金额',
          prop: 'writeOffAmount',
          width: '120px',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = formatMoneyAmount(row[prop])
            return <span>{text}</span>
          }
        },
        {
          label: '剩余金额',
          prop: 'unwritten',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = formatMoneyAmount(row[prop])
            return <span>{text}</span>
          }
        }
      ],
      rebateAccountInfo: [
        { label: '返点余额（美元）', value: '', span: 6 },
        { label: '有效截至日期', value: '', span: 6 },
        { label: '占用金额（美元）', value: '', span: 6 },
        { label: '累计已使用（美元）', value: '', span: 6 }
      ],
      creditInfo: [
        { label: '中信保授信（美元）', value: '', span: 24, itemStyle: { fontSize: '18px' }},
        { label: '授信额度', value: '' },
        { label: '占用额度', value: '' },
        { label: '剩余额度', value: '' },
        { label: '授信有效截至日期', value: '' },
        { label: '公司授信（美元）', value: '', span: 24, itemStyle: { marginTop: '30px', fontSize: '18px' }},
        { label: '授信额度', value: '' },
        { label: '占用额度', value: '' },
        { label: '剩余额度', value: '' },
        { label: '授信有效截至日期', value: '' }
      ],
      visible: false,
      activeTab: '1',
      style: {
        marginTop: '22px'
      },
      bottomStyle: {
        marginTop: '22px',
        marginBottom: '22px'
      },
      historyList: [],
      historyConfig: [
        {
          label: '核销时间',
          prop: 'writeOffTime',
          render: function(node, data) {
            const { row, column: { prop }} = data
            const text = formatTime(row[prop])
            return <span>{{ text }}</span>
          }
        },
        {
          label: '核销申请人',
          prop: 'writeOffInitiatorName',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = formatUserName(row[prop])
            return <span>{ text }</span>
          }
        },
        {
          label: '工号',
          prop: 'writeOffInitiatorNo',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = formatUserName(row[prop])
            return <span>{ text }</span>
          }
        },
        {
          label: '部门',
          prop: 'writeOffInitiatorDept',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = formatUserName(row[prop])
            return <span>{ text }</span>
          }
        },
        {
          label: 'PI编号',
          prop: 'piNo'
        },
        {
          label: '发货申请单号',
          prop: 'deliveryApplyNo'
        },
        {
          label: '回款单号',
          prop: 'paymentPlanOrderNo'
        },
        {
          label: '核销金额',
          prop: 'paymentPlanOrderWriteOffAmount',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = formatMoneyAmount(row[prop])
            return <span>{text}</span>
          }
        },
        {
          label: '币种',
          prop: 'currency',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = getDictionaryLabel(row[prop], this.currency)
            return <span>{text}</span>
          }
        },
        {
          label: '状态',
          prop: 'status',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = row[prop] === 0 ? '正常' : '已撤销'
            return <span>{text}</span>
          }
        }
      ]
    }
  },
  computed: {
    ...mapState({
      currency: state => state.base.currency,
      flow_name_type: state => state.base.flow_name_type
    })
  },
  beforeMount() {
    const { params: { id }} = this.$route
    id && (this.id = id)
    this.getDictionary()
    this.requestData()
    this.initBankInfo()
    this.initRebateAccountInfo()
    this.initCreditInfo()
    this.getWriteOffTable()
  },
  methods: {
    ...mapActions({ getBaseDataList: 'base/getBaseDataList' }),
    back() {
      this.$router.back()
    },
    getDictionary() {
      this.getBaseDataList({ type: 'currency' })
      this.getBaseDataList({ type: 'flow_name_type' })
    },
    handleHistory(id) {
      this.writeOffInfoId = id
      this.visible = true
    },
    requestData() {
      const { id } = this
      accountDetail({ id }).then(res => {
        this.allData = res
        this.initTopData(res)
      })
    },
    initTopData(data) {
      const { companyNo, companyName, countryCode, sourceCode, marketLevelCode } = data
      this.topData = { companyNo, companyName, countryCode, sourceCode, marketLevelCode }
    },
    async initBankInfo() {
      const { id } = this
      const data = await bankList({ companyId: id })
      this.bankCardInfo = data || []
    },
    async getWriteOffTable() {
      this.writeOffInfoLoading = true
      const params = {
        companyId: this.id,
        pageNum: this.writePageIndex,
        pageSize: this.writePageSize
      }
      const { records, total } = await cashBackPollList(params).finally(() => {
        this.writeOffInfoLoading = false
      })
      this.writeOffInfo = records || []
      this.writeTotal = total
    },
    handleWritePagination(data) {
      const { pageIndex, pageSize } = data
      this.writePageIndex = pageIndex
      this.writePageSize = pageSize
      this.getWriteOffTable()
    },
    async initRebateAccountInfo() {
      let data = await rebateAccountData({ companyId: this.id })
      data = data || {}
      let { balanceAmount, expiryTime, frozenAmount, usedAmount } = data
      balanceAmount = formatMoneyAmount(balanceAmount)
      expiryTime = isUndefined(expiryTime) ? '' : formatTime(expiryTime, 'YYYY-MM-DD')
      frozenAmount = formatMoneyAmount(frozenAmount)
      usedAmount = formatMoneyAmount(usedAmount)
      const arr = [balanceAmount, expiryTime, frozenAmount, usedAmount]
      arr.forEach((item, index) => {
        this.rebateAccountInfo[index].value = item
      })
    },
    async initCreditInfo() {
      const { id } = this
      let data = await getCreditInfo({ companyId: id })
      data = data || {}
      let {
        sinosureQuotaAmount,
        approvedSinosureAmount,
        notApprovedSinosureAmount,
        sinosureBalanceAmount,
        sinosureExpiryTime,
        creditQuotaAmount,
        approvedCreditAmount,
        notApprovedCreditAmount,
        creditBalanceAmount,
        creditExpiryTime
      } = data
      sinosureQuotaAmount = formatMoneyAmount(sinosureQuotaAmount)
      approvedSinosureAmount = formatMoneyAmount(approvedSinosureAmount)
      notApprovedSinosureAmount = formatMoneyAmount(notApprovedSinosureAmount)
      sinosureBalanceAmount = formatMoneyAmount(sinosureBalanceAmount)
      sinosureExpiryTime = isUndefined(sinosureExpiryTime) ? '' : formatTime(sinosureExpiryTime, 'YYYY-MM-DD')
      creditQuotaAmount = formatMoneyAmount(creditQuotaAmount)
      approvedCreditAmount = formatMoneyAmount(approvedCreditAmount)
      notApprovedCreditAmount = formatMoneyAmount(notApprovedCreditAmount)
      creditBalanceAmount = formatMoneyAmount(creditBalanceAmount)
      creditExpiryTime = isUndefined(creditExpiryTime) ? '' : formatTime(creditExpiryTime, 'YYYY-MM-DD')
      const arr = [
        '',
        sinosureQuotaAmount,
        getEngross(approvedSinosureAmount, notApprovedSinosureAmount),
        sinosureBalanceAmount,
        sinosureExpiryTime,
        '',
        creditQuotaAmount,
        getEngross(approvedCreditAmount, notApprovedCreditAmount),
        creditBalanceAmount,
        creditExpiryTime
      ]
      arr.forEach((item, index) => {
        this.creditInfo[index].value = item
      })
    },
    async openWriteHistoryDialog() {
      this.historyListLoading = true
      const data = await writeOffRecordById({ transactionFlowId: this.writeOffInfoId }).finally(() => {
        this.historyListLoading = false
      })
      this.historyList = data || []
    },
    // 清除url
    closeHandle() {
      this.curUrl = ''
      this.curName = ''
    },
    previewHandle(e, curUrl, curName) {
      e.preventDefault()
      // SF全部是新建窗口打开
      if (isSfType(curUrl)) {
        window.open(curUrl)
        return
      } else {
        window.location.href = curUrl
      }
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  margin: 12px;
  width: calc(100% - 24px);
}
</style>
